<?php
if (!defined('IN_DOUCO')) die('Hacking attempt');
header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Token,Platform,Device_id,Pf");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE');

if(!function_exists("$a")) to_ajax('000');
$a();


function initUser(){
	$user_id = rand(100000,999999);
	to_ajax('200','',array('user_id'=>$user_id));
}

function feedback(){
	global $db;
	$contact = i('contact','') == '' ? to_ajax('102','姓名不能为空') : i('contact','');
	$phone   = i('phone','') == ''   ? to_ajax('102','手机不能为空') : i('phone','');
	$address = i('address','') == '' ? to_ajax('102','地址不能为空') : i('address','');

	$count = $db->get_one("SELECT count(*) count FROM ".$db->table('guestbook')."WHERE phone='{$phone}'");
	if($count>0) to_ajax('102','该手机号已被使用~');

	$_data = array(
		'contact' => trim($contact),
		'phone'   => trim($phone),
		'address' => trim($adress),
		'prize'   => i('prize',1),
		'add_time'=> time()
	);
	$db->query( $db->insert_sql('guestbook',$_data) );
	to_ajax();
}


function upload_full(){
	$base64_img = trim($_POST['img']);
	$up_dir = 'images/full/';
	if(!file_exists(ROOT_PATH.$up_dir)) mkdir(ROOT_PATH.$up_dir,0777);
	if(!preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) to_ajax('102','图片上传类型错误~');
	$type = $result[2];
	if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
		$new_file = $up_dir.date('YmdHis').uniqid().'.'.$type;
		if(file_put_contents(ROOT_PATH.$new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
			$img_path = str_replace(ROOT_PATH, '', $new_file);
			to_ajax('200','',array('img_url'=>$new_file));
		}
	}
	to_ajax('102','上传失败~');
}


function lottery(){
	$prize_arr = prize_arr();
	foreach ($prize_arr as $key => $val) {   
    	$arr[$val['id']] = $val['rate'];   
	}
	$prize = $prize_arr[_get_rand($arr)];
	to_ajax('200','', array('prize'=>$prize));
}






function _get_rand($proArr) { 
	$result = ''; 
	//概率数组的总概率精度
	$proSum = array_sum($proArr); 
	//概率数组循环  
	foreach ($proArr as $key => $proCur) { 
		$randNum = mt_rand(1, $proSum);             
		if ($randNum <= $proCur) { 
			$result = $key;                       
			break; 
		} else { 
			$proSum -= $proCur;                     
		} 
	} 
	unset ($proArr); 
	return $result; 
}


function upload(){
	global $img_url;
	$image = upload_image('avatar','avatar');

	if(empty($image)) to_ajax('103');
	to_ajax('200','',array('image'=>$img_url.$image));
}